<template>
  <view class="container">
    <view class="list">
      <view class="box" v-for="(item, index) in list" :key="index">
        <view class="title">{{ item.company_name }}</view>
        <view class="row">
          <view class="text">岗位：</view>
          <view class="right">
            <view class="count">{{ item.post_list.length }}个</view>
            <view class="name">{{ item.post_list[0].name }}</view>
          </view>
        </view>
        <view class="row">
          <view class="text">体验时间：</view>
          <view class="right">
            <view class="time">{{ item.post_list[0].time ? item.post_list[0].time : '' }}</view>

            <view v-if="item.is_end" class="end-btn">已结束</view>
            <view v-else @click="goDetail(item.id)" class="btn">立即查看</view>
          </view>
        </view>
      </view>
    </view>

    <view id="prove-mask" v-if="show_prove" @click="empty">
      <view class="prove-mask-content" @click.stop="empty">
        <view class="prove-main-content">
          <image class="prove-close" src="/static/images/prove-close.png" @click.stop="this.show_prove = false"></image>
          <navigator hover-class="none" url="/pages/company_prove/company_prove" class="prove-box">
            <view class="line">
              <image class="icon1" src="/static/images/prove_icon2.png"></image>
              <view class="text-box">
                <view class="text">我是单位，立即认证</view>
                <view class="desc-text">申请项目、体验岗位发布</view>
              </view>
              <image class="icon2" src="/static/images/right.png"></image>
            </view>
          </navigator>
          <navigator hover-class="none" url="/pages/student_prove/student_prove" class="prove-box">
            <view class="line">
              <image class="icon1" src="/static/images/prove_icon1.png"></image>
              <view class="text-box">
                <view class="text">我是学生，立即认证</view>
                <view class="desc-text">项目体验、岗位报名</view>
              </view>
              <image class="icon2" src="/static/images/right.png"></image>
            </view>
          </navigator>
        </view>
      </view>
    </view>

    <view id="mask" v-if="show_login" @click="empty">
      <view class="mask-content" @click.stop="empty">
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="username" class="input" placeholder="请输入昵称">
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <view class="button cancel" @click="this.show_login = false">取消</view>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>

  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      list: [],
      page: 1,
      pagesize: 10,
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《金翼隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      username: '',
      show_prove: false,
    }
  },

  onShow() {
    this.page = 1;
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;

    if (!user_id) {
      uni.showLoading({
        title: '自动登录中...',
        mask: true
      })

      uni.login({
        success: result => {
          var code = result.code;

          this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
            uni.hideLoading();
            if (res.data.result == 1) {
              var user_id = res.data.data;
              uni.setStorageSync('user_id', user_id)

              this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
                if (resProve.data.result == 1) {
                  var {student_prove_id, company_prove_id} = resProve.data.data;

                  if (company_prove_id > 0) {
                    uni.setStorageSync('company_prove_id', company_prove_id);
                    uni.showToast({
                      title: '无权限',
                      icon: 'none',
                      success: () => {
                        setTimeout(() => {
                          uni.reLaunch({
                            url: '/pages/index/index'
                          })
                        }, 500)
                      }
                    })
                  }else{
                    uni.setStorageSync('student_prove_id', student_prove_id);
                  }
                }
              })
              this.projectList();
            } else {
              this.show_login = true;
            }
          })
        }
      })
    } else {
      var company_prove_id = uni.getStorageSync('company_prove_id');

      if (company_prove_id > 0) {
        uni.showToast({
          title: '无权限',
          icon: 'none',
          success: () => {
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/index/index'
              })
            }, 500)
          }
        })
      }else{
        this.projectList();
      }
    }
  },

  onPullDownRefresh() {
    this.page = 1;
    this.projectList(1, true);
  },

  onReachBottom() {
    this.projectList(this.page + 1);
  },

  methods: {
    // 项目列表
    projectList: function (incPage = 0, refreshing = false) {
      var page = incPage ? incPage : this.page;

      uni.showLoading({
        title: '数据加载中...',
        mask: true
      })

      this.$http.post('/index/Api/projectList', {
        page: page,
        pagesize: this.pagesize
      }).then((res) => {
        if (res.data.result == 1) {
          if (page == 1) {
            this.list = res.data.data;

            if(refreshing) {
              console.log('stop')
              setTimeout(() => {
                uni.stopPullDownRefresh();
              }, 300)
            }
          } else {
            // 加载更多
            var list = this.list;

            for (var i = 0; i < res.data.data.length; i++) {
              list.push(res.data.data[i]);
            }

            this.list = list;
            this.page = page;
          }

          setTimeout(() => {
            uni.hideLoading();
          }, 500)
        } else {
          if (page == 1) this.list = [];

          uni.hideLoading();
          this.$common.doErrorResult(res);
        }
      })
    },

    goDetail: function (id) {
      var student_prove_id = uni.getStorageSync('student_prove_id');
      if (student_prove_id > 0) {
        uni.navigateTo({
          url: '/pages/project_detail/project_detail?id=' + id
        })
      } else {
        this.show_prove = true;
       /* uni.navigateTo({
          url: '/pages/student_prove/student_prove'
        })*/
      }
    },

    empty: function () {
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result == 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result == 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result == 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
                      if (resProve.data.result == 1) {
                        var {student_prove_id, company_prove_id} = resProve.data.data;
                        uni.setStorageSync('student_prove_id', student_prove_id);
                        uni.setStorageSync('company_prove_id', company_prove_id);
                      }
                    })

                    this.show_login = false;

                    this.projectList();
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            })
          }
        })
      }
    },
  }
}
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background: #f5f5f5;

  .list {

    .box {
      display: flex;
      flex-direction: column;
      padding: 16rpx 24rpx;
      margin-bottom: 20rpx;
      background: #fff;
      border-radius: 20rpx;

      .title {
        font-size: 32rpx;
        font-weight: bold;
      }

      .row {
        display: flex;
        align-items: flex-start;
        margin-top: 14rpx;

        .text {
          font-size: 28rpx;
          width: 160rpx;
          font-weight: bold;
        }

        .right {
          min-width: 0;
          flex: 1;
          display: flex;
          align-items: flex-start;
          font-size: 24rpx;
          color: #555;

          .count {
            width: 100rpx;
          }

          .name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .time {
            flex: 1;
          }

          .btn {
            font-size: 24rpx;
            color: #fff;
            background: #32a4ff;
            width: 120rpx;
            height: 60rpx;
            line-height: 60rpx;
            padding: 0 24rpx;
            border-radius: 50rpx;
            text-align: center;
            margin-left: 40rpx;
          }

          .end-btn {
            font-size: 24rpx;
            color: #fff;
            background: #d9d9d9;
            width: 120rpx;
            height: 60rpx;
            line-height: 60rpx;
            padding: 0 24rpx;
            border-radius: 50rpx;
            text-align: center;
            margin-left: 40rpx;
          }
        }
      }

    }
  }


}

</style>
